package com.gsbelarus.gedemin.salary.fragment.workschedule;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.lib.Utils;
import com.gsbelarus.gedemin.lib.ui.activity.SyncActivityModel;
import com.gsbelarus.gedemin.lib.ui.activity.drawer.SyncActivityDrawerModel;
import com.gsbelarus.gedemin.lib.ui.fragment.FragmentModel;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.entity.model.DayEventModel;
import com.gsbelarus.gedemin.salary.entity.model.WorkScheduleModel;
import com.gsbelarus.gedemin.salary.util.ExtractStringHelper;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayView;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateChangedListener;

import java.util.Calendar;
import java.util.Date;

import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;

public class WorkScheduleFragment extends FragmentModel implements OnDateChangedListener, DayView.OnCreateDateViewListener {

    private RealmHelper realmHelper;

    private MaterialCalendarView calendarView;
    private ViewPager mViewPager;
//    private ExecutorService executor = Executors.newFixedThreadPool(4);

    public RealmResults<WorkScheduleModel> monthWorkSchedule;

    @Override
    public int getViewResource() {
        return R.layout.work_schedule_fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realmHelper = new RealmHelper(Realm.getInstance(context));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        realmHelper.getRealm().close();
        if (mViewPager != null)
            mViewPager.clearOnPageChangeListeners();
    }

    @Override
    public void onCreateViewFragment(View rootView) {
        super.onCreateViewFragment(rootView);
        setHasOptionsMenu(true);

        getSyncActivity().showElevationToolbar(false);

        Calendar curDate = Calendar.getInstance();
        calendarView = (MaterialCalendarView) rootView.findViewById(R.id.material_calendar_view);
        calendarView.setTitleLayoutEnabled(false);
        calendarView.setSelectedDate(curDate);
        calendarView.setOnDateChangedListener(this);
        calendarView.setOnCreateDateViewListener(this);

        mViewPager = (ViewPager) rootView.findViewById(R.id.viewPager);

        setDateToolbar(curDate.get(Calendar.MONTH), curDate.get(Calendar.YEAR));
    }

    @Override
    public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
        setDateToolbar(date.getMonth(), date.getYear());

        // выборка для месяца
        Calendar cal = Calendar.getInstance();
        cal.setTime(date.getDate());
        monthWorkSchedule = realmHelper.getMonthWorkSchedule(cal);
        mViewPager.getAdapter().notifyDataSetChanged();
    }

    @Override
    public void onDateChanged(MaterialCalendarView widget, CalendarDay date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date.getDate());
        setViewPagerDate(calendar);
    }

    @Override
    public void onCreateViewDate(final Date date, final DayView.CallBack callBack) {
//        final Handler handler = new Handler();
//        executor.execute(new Runnable() {
//            @Override
//            public void run() {
//
//                RealmHelper rm = new RealmHelper(Realm.getInstance(context));
//                WorkScheduleModel day = rm.getWorkScheduleByDay(date);
//
//                if (day != null) {
//                    RealmList<DayEventModel> dayEvents = day.getEvents();
//
//                    for (int i = 0; i < dayEvents.size(); i++) {
//                        if (ExtractStringHelper.displayedInCalDayEvent(dayEvents.get(i))) {
//                            handler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    callBack.drawUnderLine();
//                                }
//                            });
//                            break;
//                        }
//                    }
//                }
//
//                rm.getRealm().close();
//            }
//        });

        WorkScheduleModel day = realmHelper.getWorkScheduleByDay(date);

        if (day != null) {
            RealmList<DayEventModel> dayEvents = day.getEvents();

            for (int i = 0; i < dayEvents.size(); i++) {
                if (ExtractStringHelper.displayedInCalDayEvent(dayEvents.get(i))) {
                    callBack.drawUnderLine();
                    break;
                }
            }
        }
    }

    @Override
    public void readDataBase() {
    }

    @Override
    public void initView(View view) {
        monthWorkSchedule = realmHelper.getMonthWorkSchedule(Calendar.getInstance()); // TODO asynctask
        mViewPager.setAdapter(new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return monthWorkSchedule.size();
            }

            @Override
            public Fragment getItem(int pos) {
                ///TODO limit load
                return WorkScheduleDetailFragment.newInstance(monthWorkSchedule.get(pos));
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }
        });
        setViewPagerDate(Calendar.getInstance());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                calendarView.setSelectedDate(monthWorkSchedule.get(position).getDate());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setDateToolbar(int month, int year) {
        getSyncActivity().getToolbar().setTitle(
                Utils.getMonthName(getActivity().getApplicationContext(), month) + " " + year);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.work_schedule, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_today:
                calendarView.setSelectedDate(Calendar.getInstance());
                setViewPagerDate(Calendar.getInstance());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setViewPagerDate(Calendar date) {
        Calendar cal = Calendar.getInstance();
        if (monthWorkSchedule != null)
            for (int i = 0; i < monthWorkSchedule.size(); i++) {
                cal.setTime(monthWorkSchedule.get(i).getDate());
                if (cal.get(Calendar.YEAR) == date.get(Calendar.YEAR) &&
                        cal.get(Calendar.MONTH) == date.get(Calendar.MONTH) &&
                        cal.get(Calendar.DAY_OF_MONTH) == date.get(Calendar.DAY_OF_MONTH)) {
                    mViewPager.setCurrentItem(i);
                    break;
                }
            }
    }

    private SyncActivityDrawerModel getSyncActivity() {
        return (SyncActivityDrawerModel) getActivity();
    }

    @Override
    public void onStart() {
        super.onStart();
        ((SyncActivityModel) getActivity()).showElevationToolbar(false);
    }

    @Override
    public void onStop() {
        super.onStop();
        ((SyncActivityModel) getActivity()).showElevationToolbar(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        Tracker tracker = ((App) getActivity().getApplication()).getTracker(App.TrackerName.APP_TRACKER);
        tracker.setScreenName(getClass().getSimpleName());
        tracker.send(new HitBuilders.AppViewBuilder().build());
    }
}
